package com.TexasHoldem.util;

import java.io.IOException;

import javax.management.ObjectName;

import mx4j.tools.adaptor.http.HttpAdaptor;

import org.springframework.context.ApplicationContext;
import org.springframework.jmx.export.MBeanExporter;

public class SpringFactory {
	
	private static ApplicationContext context;
	private static org.springframework.jmx.export.MBeanExporter mBeanExporter;
	
	public static void init(ApplicationContext ctx) {
		context = ctx;
		mBeanExporter = (MBeanExporter) context.getBean("exporter");
	}
	
	public static void startJmxHttpAdaptor() throws IOException {
		HttpAdaptor httpAdaptor = (HttpAdaptor) getBean("httpAdaptor");
		if (!httpAdaptor.isActive()) {
			httpAdaptor.start();
		}
	}
	public static Object getBean(String beanName) {
		return context.getBean(beanName);
	}
	
	public static void register(Object obj, String domain, String name) {
		try {
			ObjectName oname = ObjectName.getInstance(domain + ":name=" + name);
			if (!mBeanExporter.getServer().isRegistered(oname)) {
				mBeanExporter.registerManagedResource(obj, oname);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void unRegister(String domain, String name) {
		try {
			ObjectName oname = ObjectName.getInstance(domain + ":name=" + name);
			if (mBeanExporter.getServer().isRegistered(oname)) {
				mBeanExporter.getServer().unregisterMBean(oname);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
